package com.zcxy.sys.service.impl;

import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.zcxy.exception.BusinessException;
import com.zcxy.sys.config.EmailConfig;
import com.zcxy.sys.service.IEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @author xl
 * @date 2019-12-26
 */
@Service
@CacheConfig(cacheNames = "email")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class EmailServiceImpl implements IEmailService {
    @Autowired
    private EmailConfig emailConfig;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void send(com.zcxy.sys.pojo.EmailVo emailVo) {
        if (emailConfig == null || StringUtils.isEmpty(emailConfig.getUser())) {
            throw new BusinessException("请先配置，再操作");
        }
        // 封装
        MailAccount account = new MailAccount();
        account.setHost(emailConfig.getHost());
        account.setPort(Integer.parseInt(emailConfig.getPort()));
        account.setAuth(true);
        // 对称解密
        account.setPass(emailConfig.getPass());
        account.setFrom(emailConfig.getUser());
        // ssl方式发送
        account.setSslEnable(true);
        account.setUser(emailConfig.getUser());
        String content = emailVo.getContent();
        account.setSocketFactoryClass("com.sun.mail.util.MailSSLSocketFactory");
        account.setSocketFactoryPort(465);
        //密码
        // 发送
        try {
            int size = emailVo.getTos().size();
            Mail.create(account).setTos(emailVo.getTos().toArray(new String[size])).setTitle(emailVo.getSubject())
                    .setContent(content).setHtml(true)
                    //关闭session
                    .setUseGlobalSession(false).send();
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }


}
